package com.xnfh.common.task

import android.app.Activity
import android.app.Application
import com.alibaba.android.arouter.launcher.ARouter
import com.tencent.mmkv.MMKV
import com.tencent.mmkv.MMKVLogLevel
import com.xnfh.framework.helper.SumAppHelper
import com.xnfh.framework.log.LogUtil
import com.xnfh.stater.task.Task
import com.xnfh.stater.utils.DispatcherExecutor
import java.util.concurrent.ExecutorService
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.tencent.smtt.export.external.TbsCoreSettings
import com.tencent.smtt.sdk.QbSdk
import com.xnfh.common.BuildConfig
import com.xnfh.framework.Constants.SCREEN_WITH
import com.xnfh.framework.Constants.SCREEN_WITH_HORIZONTAL
import com.xnfh.framework.ext.isPortrait
import me.jessyan.autosize.AutoSizeConfig
import me.jessyan.autosize.onAdaptListener
import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.HttpsURLConnection
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager


/**
 * @Description:
 * @Author: ziheng
 * @CreateDate: 2023/11/7 09:49
 * @UpdateUser: ziheng
 * @UpdateDate: 2023/11/7 09:49
 * @UpdateRemark: 更新说明
 */

/**
 * 初始化全局帮助类
 */
class InitSumHelperTask(val application: Application) : Task() {
    //异步线程执行的Task在被调用await的时候等待
    override fun needWait(): Boolean {
        return true
    }

    override fun run() {
        SumAppHelper.init(application, BuildConfig.DEBUG)
    }
}

/**
 * 初始化MMKV
 */
class InitMmkvTask : Task() {

    //异步线程执行的Task在被调用await的时候等待
    override fun needWait(): Boolean {
        return true
    }

    //依赖某些任务，在某些任务完成后才能执行
    override fun dependsOn(): MutableList<Class<out Task>> {
        val tasks = mutableListOf<Class<out Task?>>()
        tasks.add(InitSumHelperTask::class.java)
        return tasks
    }

    //指定线程池
    override fun runOn(): ExecutorService? {
        return DispatcherExecutor.iOExecutor
    }

    //执行任务初始化
    override fun run() {
        val rootDir: String = MMKV.initialize(SumAppHelper.getApplication())
        MMKV.setLogLevel(
            if (BuildConfig.DEBUG) {
                MMKVLogLevel.LevelDebug
            } else {
                MMKVLogLevel.LevelError
            }
        )
        LogUtil.d("mmkv root: $rootDir", tag = "MMKV")
    }
}

/**
 * 全局初始化SmartRefreshLayout
 */
class InitRefreshLayoutTask : Task() {
    //异步线程执行的Task在被调用await的时候等待
    override fun needWait(): Boolean {
        return true
    }

    override fun run() {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator { context, layout ->
            layout.setPrimaryColorsId(android.R.color.white)
//            CustomRefreshHeader(context)
            ClassicsHeader(context)
        }
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator { context, layout ->
            //指定为经典Footer，默认是 BallPulseFooter
            ClassicsFooter(context)
        }
    }
}

/**
 * 初始化ShareManager
 */
class InitArouterTask : Task() {
    //异步线程执行的Task在被调用await的时候等待
    override fun needWait(): Boolean {
        return true
    }

    //依赖某些任务，在某些任务完成后才能执行
    override fun dependsOn(): MutableList<Class<out Task>> {
        val tasks = mutableListOf<Class<out Task?>>()
        tasks.add(InitSumHelperTask::class.java)
        return tasks
    }

    //执行任务，任务真正的执行逻辑
    override fun run() {
        // 这两行必须写在init之前，否则这些配置在init过程中将无效
        if (BuildConfig.DEBUG) {
            // 开启打印日志
            ARouter.openLog()
            // 开启调试模式(如果在InstantRun模式下运行，必须开启调试模式！线上版本需要关闭,否则有安全风险)
            ARouter.openDebug()
        }
        ARouter.init(SumAppHelper.getApplication())
    }
}

class InitAutoSizeTask: Task(){
    override fun needWait(): Boolean {
        return true
    }
    override fun run() {
        AutoSizeConfig.getInstance().onAdaptListener = object : onAdaptListener {
            override fun onAdaptBefore(target: Any, activity: Activity?) {
                if (isPortrait(activity!!)) {
                    AutoSizeConfig.getInstance().designWidthInDp = SCREEN_WITH
                } else {
                    AutoSizeConfig.getInstance().designWidthInDp =
                        SCREEN_WITH_HORIZONTAL
                }
            }

            override fun onAdaptAfter(target: Any?, activity: Activity?) {}
        }
    }
}
class InitX5WebviewTask: Task(){
    override fun needWait(): Boolean {
        return false
    }

    override fun dependsOn(): List<Class<out Task?>?>? {
        val tasks = mutableListOf<Class<out Task?>>()
        tasks.add(InitSumHelperTask::class.java)
        return tasks
    }

    override fun run() {
        // 在调用TBS初始化、创建WebView之前进行如下配置
        val map = HashMap<String, Any>()
        map[TbsCoreSettings.TBS_SETTINGS_USE_SPEEDY_CLASSLOADER] = true
        map[TbsCoreSettings.TBS_SETTINGS_USE_DEXLOADER_SERVICE] = true
        QbSdk.initTbsSettings(map)
        QbSdk.initX5Environment(SumAppHelper.getApplication(), object : QbSdk.PreInitCallback {
            override fun onCoreInitFinished() {
                // 内核初始化完成
            }

            /**
             * 预初始化结束
             * 由于X5内核体积较大，需要依赖网络动态下发，所以当内核不存在的时候，默认会回调false，此时将会使用系统内核代替
             * @param isX5 是否使用X5内核
             */
            override fun onViewInitFinished(p0: Boolean) {
            }
        })
    }
}

/**
 * 忽略https的证书校验
 */
class handleSSLHandshakeTask: Task(){
    override fun run() {
        try {
            val trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
                override fun getAcceptedIssuers(): Array<X509Certificate?> {
                    return arrayOfNulls<X509Certificate>(0)
                }

                override fun checkClientTrusted(
                    certs: Array<X509Certificate?>?,
                    authType: String?
                ) {
                }

                override fun checkServerTrusted(
                    certs: Array<X509Certificate?>?,
                    authType: String?
                ) {
                }
            })
            val sc = SSLContext.getInstance("TLS")
            // trustAllCerts信任所有的证书
            sc.init(null, trustAllCerts, SecureRandom())
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.socketFactory)
            HttpsURLConnection.setDefaultHostnameVerifier { hostname, session -> true }
        } catch (ignored: Exception) {
            LogUtil.e(ignored.message.toString())
        }
    }

}